<template>
  <div>
    <el-container class="index-container">
      <el-header>
        <div>
          <el-avatar :size="50" :src="circleUrl"></el-avatar>
          <span>{{userName}}的计划</span>
        </div>
        <el-dropdown @command="menuClick">
          <el-button type="primary">
            更多菜单
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="d">首页</el-dropdown-item>
            <el-dropdown-item command="c">密码备忘</el-dropdown-item>
            <el-dropdown-item command="b">用户设置</el-dropdown-item>
            <el-dropdown-item command="a">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-header>
      <el-main>
        <!-- 路由占位符 -->
        <router-view></router-view>
        <div class="footerDiv"> 互联网ICP备案：<a href="http://beian.miit.gov.cn/">赣ICP备2020011084号</a></div>
      </el-main>
    </el-container>

    <!-- 用户设置对话框 -->
    <el-dialog
      title="用户设置"
      :visible.sync="dialogVisible"
      width="50%">
      <span>头像上传</span>
      <el-upload
        class="avatar-uploader"
        :action="actionUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="headerObj"
        name="upload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-form :label-position="labelPosition" :model="updateUserForm" :rules="updateUserFormRules" ref="updateUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="userN">
          <el-input v-model="updateUserForm.userN" ></el-input>
        </el-form-item>
         <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="updateUserForm.userEmail" ></el-input>
        </el-form-item>
         <el-form-item label="手机" prop="userMobile">
          <el-input v-model="updateUserForm.userMobile" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="agreeUserSetting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 提示用户输入密码 -->
    <el-dialog
      title="请输入密码"
      :visible.sync="confirmDialogVisible"
      width="500px"
      @closed="confirmDialogClose">
      <el-form :label-position="labelPosition" :model="confirmPasswordForm" :rules="confirmPasswordRules" ref="confirmPasswordRef" label-width="100px">
        <el-form-item label="密码" prop="confirmPass">
          <el-input v-model="confirmPasswordForm.confirmPass" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPass">确 定</el-button>
      </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      var reg = new RegExp(
        '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
      ) // 正则表达式
      if (value === '') {
        // 输入不能为空
        callback(new Error('请输入邮箱'))
        return false
      } else if (!reg.test(value)) {
        // 正则验证不通过，格式不对
        callback(new Error('请输入正确的邮箱'))
        return false
      } else {
        callback()
      }
    }
    return {
      // 后台获取的头像路径
      circleUrl: '',
      imageUrl: '',
      dialogVisible: false,
      updateUserForm: {
        userN: '',
        userEmail: '',
        userMobile: 0
      },
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization:
        window.sessionStorage.getItem('token')
      },
      actionUrl: 'https://www.seeklife.site:9100/yourplan/user/fileupload',
      userName: '',
      // 确认密码表单的显示与否
      confirmDialogVisible: false,
      confirmPasswordRules: {
        confirmPass: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      updateUserFormRules: {
        userN: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        userEmail: [
          { validator: validateEmail, message: '请输入邮箱', trigger: 'blur' }
        ],
        userMobile: [
          { required: false, message: '请输入手机', trigger: 'blur' }
        ]
      },
      // 确认密码表单数据
      confirmPasswordForm: {
        confirmPass: ''
      },
      // 表单对齐方式
      labelPosition: 'top',
      // 下拉菜单索引
      index: 'd'
    }
  },
  created() {
    // 请求头像路径
    this.getUserAvatarAndUser()
  },
  methods: {
    menuClick(command) {
      if (command === 'a') {
        this.index = command
        console.log('点击了退出')
        window.sessionStorage.clear()
        this.$router.push('/login')
      } else if (command === 'b') {
        this.dialogVisible = true
      } else if (command === 'c') {
        if (this.index !== 'c') {
          // 弹出一个对话框提示用户再次输入密码
          this.confirmDialogVisible = true
        }
      } else if (command === 'd') {
        if (this.index !== 'd') {
          this.index = command
          this.$router.push('/home')
        }
      }
    },
    // 监听上传头像成功方法
    handleAvatarSuccess(response) {
      this.imageUrl = response.data.pic_path
    },
    // 头像上传之前验证图片是否符合标准
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 确定使用修改后的用户设置
    agreeUserSetting() {
      // 提交表单修改的用户名称
      // 正式提交之前需要验证
      this.$refs.updateUserFormRef.validate(async valid => {
        if (!valid) return
        // 执行提交操作
        const { data: res } = await this.$http.post('/user/updateUser', this.updateUserForm)
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户失败')
        }
        this.$message.success('修改用户成功')
        this.dialogVisible = false
        // 调用后台查询数据库得到Url然后赋值
        this.getUserAvatarAndUser()
      })
    },
    // 获取用户头像
    async getUserAvatarAndUser() {
      const { data: res } = await this.$http.get('/user/getAvatarAndUser')
      if (res.meta.status !== 200) {
        return this.$message.error('获取头像失败')
      }
      this.circleUrl = res.data.avatar
      this.userName = res.data.username
      this.updateUserForm.userN = this.userName
      this.updateUserForm.userEmail = res.data.email
      this.updateUserForm.userMobile = res.data.userMobile
      console.log('获取的头像链接' + this.circleUrl)
    },
    // 确认密码
    confirmPass() {
      // 正式提交之前需要验证
      this.$refs.confirmPasswordRef.validate(async valid => {
        if (!valid) return
        // 执行提交操作
        const { data: res } = await this.$http.post('/pm/confirm', this.confirmPasswordForm)
        if (res.meta.status !== 200) {
          return this.$message.error('认证失败')
        }
        // 编程式跳转
        this.$router.push('/passManager')
        // 关闭对话框
        this.confirmDialogVisible = false
        this.$refs.confirmPasswordRef.resetFields()
        // 置空表单数据
        this.confirmPasswordForm.confirmPass = ''
        // 给下拉菜单索引赋值
        this.index = 'c'
      })
    },
    // 监听对话框关闭事件
    confirmDialogClose() {
      console.log('对话框关闭')
      this.$refs.confirmPasswordRef.resetFields()
      // 置空表单数据
      this.confirmPasswordForm.confirmPass = ''
    }
  }
}
</script>

<style lang="less" scoped>
.index-container {
  height: 100%;
}

.el-header {
  min-width: 1000px;
  background-color: #606266;
  display: flex;
  justify-content: space-between;
  padding-left: 0;
  align-items: center;
  color: #fff;
}

.el-header div {
  display: flex;
  align-items: center;
}

.el-header div span {
  margin-left: 15px;
}

.el-main {
  // width: 100%;
  // height: 100%;
  // box-sizing: content-box !important;
  min-width: 1000px;
  overflow: hidden;
  padding: 0px !important;
}

// 上图头像样式
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 178px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .footerDiv {
    // width: 100%;
    color: #fff;
    font-size: 14px;
    background-color: #606266;
    text-align: center;
    padding: 2px;
    a {
      color: #fff;
      text-decoration: none;
    }
    a:hover {
      color: #008cff;
    }
  }
</style>
